#include <DHT.h>
// 包含头文件
//#include "DHT.h"
#define DHTPIN 2
//2号作为温湿度传感器的引脚    
#define DHTTYPE DHT11  
//指明传感器类型 DHT11
DHT dht(DHTPIN, DHTTYPE);
#include <LiquidCrystal.h> 
// 初始化引脚
#define printByte(args) write(args);
LiquidCrystal lcd(12, 11, 6, 5, 4, 3); 
//自定义摄氏度的字符
uint8_t sheshidu[8]={0x08,0x14,0x08,0x07,0x04,0x04,0x04,0x07,};
//自定义百分号 %
uint8_t wenleft[8] = {0x1D,0x15,0x1D,0x06,0x0C,0x17,0x15,0x17,};

const int button_low = 10;//定义减小斜率的引脚
const int button_high = 8;//定义增大斜率的引脚

long lastbuttonstate =  LOW;//定义上次开关状态
long lastbuttontime = 0;//定义一个时间
long debouncetime = 50;//定义防抖动时间
long buttonstate=LOW ;//定义开关的现在的状态

long lastbuttonstate2 =  LOW;
long lastbuttontime2 = 0;
long buttonstate2=LOW ;

int outputPin = 9;//PWM output
float base_C = 10.00;
// 基本最低温度，达到此温度风扇不工作，可以修改数值。
int K_of_line = 5;
//设置风扇调速斜率的默认值。
int measurePin = A3;
//定义风扇测速识别引脚
void setup() { 
 // 初始化斜率
 K_of_line = 5;
 //初始化引脚
 pinMode(outputPin,OUTPUT);
 pinMode(button_low,INPUT);
 pinMode(button_high,INPUT);
 //初始化1602液晶显示屏
 lcd.begin(16, 2); 
 //初始化温湿度传感器 串口通信
 Serial.begin(9600);
 Serial.println("test!");
 dht.begin();
 //创建自定义字符的编号
 lcd.createChar(0,sheshidu);
 lcd.createChar(1,wenleft);
} 
void loop() 
{ 
  //两个开关的相关防抖动程序
  int reading1 = digitalRead(button_low);
  int reading2 = digitalRead(button_high);
  // 左边开关减少斜率的程序
  if(reading1 != buttonstate)
  {
    long lastbuttontime = millis();
  }
if( ( millis()-lastbuttontime) > debouncetime )
    {
       if(reading1 != buttonstate)
      {
         reading1 = buttonstate;
         K_of_line-=2;//可修改
         delay(1000);//两次有效按键的延时.
      } 
     }

  //右边开关增加斜率的程序
     if(reading2 != buttonstate2)
  {
    long lastbuttontime2 = millis();
  }
if( ( millis()-lastbuttontime2) > debouncetime )
    {
       if(reading2 != buttonstate2)
      {
         reading2 = buttonstate2;
         K_of_line+=2;//可修改
         delay(1000);//两次有效按键的延时.
      } 
     }
  float t = dht.readTemperature(); 
  //判断是否为空值，以保证数值有效
  if (isnan(t)) 
  {
    Serial.println("Failed to read from DHT sensor!");
    lcd.print("Error!");
    return;
  }
 //风扇测速模块
 float vshow,timesum=0;
 for(int i=0;i<10;i++)
 {//测量十次，减少误差
  timesum=timesum+pulseIn(measurePin,HIGH);
  timesum=timesum+pulseIn(measurePin,LOW);  
 }
  float zhuan=timesum/5;//取平均值
  vshow=60*1000000/zhuan;//单位转换
  timesum=0;//恢复初始值
  delay(50);

  int value1 = (int)(t-base_C)*K_of_line;
  // 数据处理
  if(value1>=0 || value1<=255)// PWM波输出
  analogWrite(outputPin,value1);
  int value2 = value1*100/255;// 转速表示
  int value3 = (K_of_line+0.5)*100/255; //斜率表示
  //1602液晶显示屏的显示部分
  lcd.setCursor(0,0);
  lcd.print("T:");
  lcd.print(t); 
  lcd.write(byte(0));// 打印摄氏度符号
  lcd.print(" ");
  //显示斜率
  lcd.print("K:");
  lcd.print(value3);
  //显示转速
  lcd.setCursor(0,1);
  lcd.print("V:");
  if(value2>0)
  lcd.print(vshow);
  else 
  lcd.print("0");
  //显示单位
  lcd.setCursor(10,1);
  lcd.print("r/min");
}
